// 围栏管理器
export default class FenceManager {
  constructor(options) {
    this.map = options.map
    this.style = options.style || this.getDefaultStyle()
    this.onFenceChange = options.onFenceChange
    this.onEditStart = options.onEditStart
    this.onEditEnd = options.onEditEnd
    
    this.polygon = null
    this.tempPolygon = null
    this.isEditing = false
    this.editPoints = []
    this.markers = []
    
    this.init()
  }
  
  // 默认样式
  getDefaultStyle() {
    return {
      strokeColor: '#3366FF',
      strokeWeight: 2,
      fillColor: '#3366FF',
      fillOpacity: 0.2,
      strokeStyle: 'solid'
    }
  }
  
  init() {
    // 绑定地图事件
    this.bindMapEvents()
  }
  
  // 绑定地图事件
  bindMapEvents() {
    this.mapClickHandler = this.handleMapClick.bind(this)
    this.mapRightClickHandler = this.handleRightClick.bind(this)
    
    this.map.on('click', this.mapClickHandler)
    this.map.on('rightclick', this.mapRightClickHandler)
  }
  
  // 解绑地图事件
  unbindMapEvents() {
    this.map.off('click', this.mapClickHandler)
    this.map.off('rightclick', this.mapRightClickHandler)
  }
  
  // 开始编辑模式
  startEdit() {
    this.clear()
    this.isEditing = true
    this.editPoints = []
    this.clearMarkers()
    this.onEditStart && this.onEditStart()
    
    // 修改鼠标样式提示用户可以点击
    this.map.getContainer().style.cursor = 'crosshair'
  }
  
  // 处理地图点击
  handleMapClick(e) {
    if (!this.isEditing) return
    
    const point = [e.lnglat.lng, e.lnglat.lat]
    this.editPoints.push(point)
    
    // 添加点标记
    this.addPointMarker(point, this.editPoints.length)
    
    // 如果有3个以上点，绘制临时围栏
    if (this.editPoints.length >= 3) {
      this.drawTemporaryFence()
    }
  }
  
  // 添加点标记
  addPointMarker(point, index) {
    const marker = new AMap.Marker({
      position: point,
      content: `<div style="
        background: #3366FF;
        color: white;
        border-radius: 50%;
        width: 24px;
        height: 24px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        font-weight: bold;
        border: 2px solid white;
        box-shadow: 0 2px 4px rgba(0,0,0,0.3);
      ">${index}</div>`,
      offset: new AMap.Pixel(-12, -12)
    })
    
    this.map.add(marker)
    this.markers.push(marker)
  }
  
  // 清除所有标记
  clearMarkers() {
    this.markers.forEach(marker => {
      this.map.remove(marker)
    })
    this.markers = []
  }
  
  // 处理右键点击（完成编辑）
  handleRightClick(e) {
    if (!this.isEditing || this.editPoints.length < 3) {
      if (this.isEditing && this.editPoints.length > 0) {
        this.$message && this.$message.warning('至少需要3个点才能形成围栏')
      }
      return
    }
    
    this.finishEdit()
  }
  
  // 绘制临时围栏
  drawTemporaryFence() {
    if (this.editPoints.length < 3) return
    
    // 移除之前的临时多边形
    if (this.tempPolygon) {
      this.map.remove(this.tempPolygon)
    }
    
    // 创建临时多边形预览
    this.tempPolygon = new AMap.Polygon({
      path: this.editPoints,
      strokeColor: this.style.strokeColor,
      strokeWeight: this.style.strokeWeight,
      fillColor: this.style.fillColor,
      fillOpacity: this.style.fillOpacity * 0.5,
      strokeStyle: 'dashed' // 临时围栏使用虚线
    })
    
    this.map.add(this.tempPolygon)
  }
  
  // 完成编辑
  finishEdit() {
    this.isEditing = false
    
    // 恢复鼠标样式
    this.map.getContainer().style.cursor = ''
    
    // 移除临时围栏和标记
    if (this.tempPolygon) {
      this.map.remove(this.tempPolygon)
      this.tempPolygon = null
    }
    this.clearMarkers()
    
    // 创建正式围栏
    if (this.editPoints.length >= 3) {
      this.createFence(this.editPoints)
    }
    
    this.editPoints = []
    this.onEditEnd && this.onEditEnd()
  }
  
  // 创建围栏
  createFence(coordinates) {
    this.clear()
    
    this.polygon = new AMap.Polygon({
      path: coordinates,
      strokeColor: this.style.strokeColor,
      strokeWeight: this.style.strokeWeight,
      fillColor: this.style.fillColor,
      fillOpacity: this.style.fillOpacity,
      strokeStyle: this.style.strokeStyle
    })
    
    this.map.add(this.polygon)
    
    // 适配地图视野到围栏区域
    this.fitViewToFence()
    
    this.onFenceChange && this.onFenceChange(coordinates, 'create')
  }
  
  // 更新围栏
  updateFence(coordinates) {
    this.clear()
    
    if (coordinates && coordinates.length > 0) {
      this.polygon = new AMap.Polygon({
        path: coordinates,
        strokeColor: this.style.strokeColor,
        strokeWeight: this.style.strokeWeight,
        fillColor: this.style.fillColor,
        fillOpacity: this.style.fillOpacity,
        strokeStyle: this.style.strokeStyle
      })
      
      this.map.add(this.polygon)
      
      // 适配地图视野到围栏区域
      this.fitViewToFence()
    }
  }
  
  // 适配地图视野到围栏
  fitViewToFence() {
    if (this.polygon) {
      try {
        this.map.setFitView([this.polygon], false, [20, 20, 20, 20])
      } catch (error) {
        console.warn('适配围栏视野失败:', error)
      }
    }
  }
  
  // 清除围栏
  clear() {
    if (this.polygon) {
      this.map.remove(this.polygon)
      this.polygon = null
    }
    
    if (this.tempPolygon) {
      this.map.remove(this.tempPolygon)
      this.tempPolygon = null
    }
    
    this.clearMarkers()
  }
  
  // 获取当前围栏坐标
  getFenceCoordinates() {
    if (this.polygon) {
      return this.polygon.getPath()
    }
    return []
  }
  
  // 销毁管理器
  destroy() {
    this.clear()
    this.unbindMapEvents()
    this.isEditing = false
    this.editPoints = []
  }
  
  // 更新样式
  updateStyle(newStyle) {
    this.style = { ...this.style, ...newStyle }
    
    if (this.polygon) {
      this.polygon.setOptions(this.style)
    }
  }
} 